<!-- Form -->
<template>
  <el-form
    ref="elForm"
    :label-width="$attrs.labelWidth || '80px'"
    v-bind="$attrs"
    v-on="$listeners"
    @submit.native.prevent
  >
    <el-row :gutter="12">
      <el-col
        v-for="(item, index) in itemsDatas"
        v-show="!item.hidden"
        :key="item.label + item.prop + index"
        :md="item.md || md"
        :lg="item.lg || lg"
        :xl="item.xl || xl"
        :span="item.span || span"
      >
        <form-item :item="item" :form-datas="formDatas">
          <template v-if="item.type=='slot'">
            <slot :slot="item.prop" :name="item.prop || item.slotName" :item="item" :form-data="formDatas" />
          </template>
        </form-item>
        <el-col />
      </el-col>
      <el-col
        class="handle-right"
        :md="12"
        :lg="8"
        :xl="6"
      >
        <slot />
      </el-col>
    </el-row>
  </el-form>
</template>

<script>
export default {
  name: 'MyForm',
  components: {},

  props: {
    // 默认响应式布局 md=12 lg=8 xl=6
    isGrid: { type: Boolean, default: true },
    // 全局控制item的span， 默认8，只有isGrid为false才能用
    itemSpan: { type: Number, default: 8 },
    itemsDatas: { type: Array, default: () => [] },
    formDatas: { type: Object, default: () => {} }
  },
  data() {
    return {
    }
  },

  computed: {
    md() {
      return this.isGrid ? 12 : ''
    },
    lg() {
      return this.isGrid ? 8 : ''
    },
    xl() {
      return this.isGrid ? 6 : ''
    },
    span() {
      // 响应式布局的时候，没有span的设置
      return this.isGrid ? null : this.itemSpan
    }
  },

  mounted() {
    this.$on('validate', this.validate)
    this.$on('resetFields', this.resetFields)
  },
  beforeDestroy() {
    this.$off('validate')
    this.$off('resetFields')
  },

  methods: {
    validate(fn = () => {}) {
      this.$refs['elForm'].validate(valid => {
        fn(valid)
      })
    },
    resetFields() {
      this.$refs['elForm'].resetFields()
    }
  }
}

</script>
<style lang='scss' scoped>
.handle-right {
  float: right;
  text-align: right;
}
</style>
